package com.ls.service.impl;

import com.ls.service.DataService;
import com.ls.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author ls
 * @version v1.0
 * @description
 * @date 2021/8/23 23:48
 */
@Service
public class DataServiceImpl implements DataService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void recodeUv(String ip) {
        String uvKey = RedisKeyUtil.getUVKey(sdf.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(uvKey, ip);
    }

    @Override
    public long countUv(Date start, Date end) {
        if (start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        // 整理该日期范围内的key
        List<String> uvKeys = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) {
            String uvKey = RedisKeyUtil.getUVKey(sdf.format(calendar.getTime()));
            uvKeys.add(uvKey);
            calendar.add(Calendar.DATE, 1);
        }
        // 合并数据
        String redisKey = RedisKeyUtil.getUVKey(sdf.format(start), sdf.format(end));
        redisTemplate.opsForHyperLogLog().union(redisKey, uvKeys.toArray(new String[0]));
        // 返回统计结果
        return redisTemplate.opsForHyperLogLog().size(redisKey);
    }

    @Override
    public void recodeDau(int userId) {
        String dauKey = RedisKeyUtil.getDAUKey(sdf.format(new Date()));
        // 存储每天活跃用户, 用户id为索引
        redisTemplate.opsForValue().setBit(dauKey, userId, true);
    }

    @Override
    public long countDau(Date start, Date end) {
        if (start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        // 整理该日期范围内的key
        List<byte[]> dauKeys = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) {
            String dauKey = RedisKeyUtil.getDAUKey(sdf.format(calendar.getTime()));
            dauKeys.add(dauKey.getBytes());
            calendar.add(Calendar.DATE, 1);
        }

        Object activeNumber = redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                String redisKey = RedisKeyUtil.getDAUKey(sdf.format(start), sdf.format(end));
                connection.bitOp(RedisStringCommands.BitOperation.OR,
                        redisKey.getBytes(),
                        dauKeys.toArray(new byte[0][0]));
                return connection.bitCount(redisKey.getBytes());
            }
        });
        return activeNumber == null ? 0 : (long) activeNumber;
    }
}
